package com.qujia.markert.controller;

import com.alibaba.fastjson.JSONObject;
import com.qujia.common.annotation.Log;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.enums.BusinessType;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.poi.ExcelUtil;
import com.qujia.customer.domain.ActivityMessagePushRecord;
import com.qujia.customer.enums.ElectronCardType;
import com.qujia.customer.service.ActivityMessagePushRecordService;
import com.qujia.markert.domain.ReductionActivity;
import com.qujia.markert.service.IReductionActivityService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * 立减活动Controller
 * 
 * @author qujia
 * @date 2021-11-02
 */
@RestController
@RequestMapping("/market/reductionActivity")
public class ReductionActivityController extends BaseController
{
    @Autowired
    private IReductionActivityService reductionActivityService;
    @Autowired
    private ActivityMessagePushRecordService activityMessagePushRecordService;


    private static final Map<String,String> activityUseMap = new HashMap<>();
    private static final  Map<String,String> activityTypeMap = new HashMap<>();
    private static final Map<String,String> activityModeMap = new HashMap<>();
    private static final Map<String,String> payModeMap = new HashMap<>();
    private static final Map<String,String> gradeMap = new HashMap<>();
    private static final Map<String,String> memberCategoryMap = new HashMap<>();

    private static final Map<String,String> cardTypeMap = new HashMap<>();
    private static final Map<String,String> physicalCardTypeMap = new HashMap<>();

    static {
        activityUseMap.put("CSP","消费");
        activityUseMap.put("RCH","充值");
        activityUseMap.put("LABEl","标签");
        activityTypeMap.put("RFA","按固定金额");
        activityTypeMap.put("LOR","按固定数量");
        activityTypeMap.put("AAL","每升立减(以金额为门槛)");
        activityTypeMap.put("AALL","每升立减(以升数为门槛)");
        activityModeMap.put("FAD","定额立减");
        activityModeMap.put("PAR","百分比立减");
        activityModeMap.put("RDD","随机立减");

        payModeMap.put("wx","微信");
        payModeMap.put("zfb","支付宝");
        payModeMap.put("dzk","电子卡");
        payModeMap.put("xj","现金");
        payModeMap.put("yl","刷卡");
        payModeMap.put("yhk","银行卡");
        payModeMap.put("dkq","实体卡");
        payModeMap.put("pos","POS扫码");
        payModeMap.put("cdk","车队卡");
        gradeMap.put("1","普卡");
        gradeMap.put("2","银卡");
        gradeMap.put("3","金卡");
        gradeMap.put("4","钻卡");
        gradeMap.put("5","黑卡");
        gradeMap.put("96","超级会员-月卡");
        gradeMap.put("97","超级会员-季卡");
        gradeMap.put("98","超级会员-年卡");
        gradeMap.put("99","超级会员");

        memberCategoryMap.put("new","新用户");
        memberCategoryMap.put("old","老用户");

        ElectronCardType[] cardTypes = ElectronCardType.values();
        for (ElectronCardType cardType : cardTypes) {
            cardTypeMap.put(cardType.getKey(),cardType.getName()+"卡");
            physicalCardTypeMap.put(cardType.getKey(),"实体"+cardType.getName()+"卡");
        }
        physicalCardTypeMap.put("dek","实体定额卡");

    }
    /**
     * 查询立减活动列表
     */
    @GetMapping("/list")
    public TableDataInfo list(ReductionActivity reductionActivity)
    {
        startPage();
        List<ReductionActivity> list = reductionActivityService.selectActivityByLoginUser(reductionActivity);
// 获取当前日期时间
        LocalDateTime today = LocalDateTime.now();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        for (ReductionActivity activity : list) {
            // 将活动的开始日期和结束日期转换为字符串类型
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String startDateStr = sdf.format(activity.getStartDate());
            String endDateStr = sdf.format(activity.getEndDate());

            // 将活动的开始日期和结束日期解析为LocalDateTime类型
            LocalDateTime startDate = LocalDateTime.parse(startDateStr, formatter);
            LocalDateTime endDate = LocalDateTime.parse(endDateStr, formatter);

            // 检查当前日期是否在活动日期范围内
            if (today.isAfter(startDate) && today.isBefore(endDate)) {
                activity.setActivityStatus("1");
            }else{
                activity.setActivityStatus("0");
            }

            //activity.setMemberLevel(gradeMap.get(activity.getMemberLevel()));
            if(activity.getPaymentMethod()!=null&&!activity.getPaymentMethod().contains(",")){
                activity.setPaymentMethod(payModeMap.get(activity.getPaymentMethod()));
                if(activity.getPaymentMethod()==null){
                    activity.setPaymentMethod("");
                }
                if(activity.getPaymentMethod().equals("现金")&&activity.getActivityUse().equals("RCH")){
                    //充值立减活动 手动增加用的现金的枚举值
                    activity.setPaymentMethod("手动增加");
                }
            }
            if(activity.getPaymentMethod()!=null&&activity.getPaymentMethod().contains(",")){
                String[] split = activity.getPaymentMethod().split(",");
                String pm="";
                for (String s : split) {
                    String s1 = payModeMap.get(s);
                    if(s1==null){
                        s1="";
                    }
                    if(s1.equals("现金")&&activity.getActivityUse().equals("RCH")){
                        //充值立减活动 手动增加用的现金的枚举值
                        s1="手动增加";
                    }
                    pm=pm+","+s1;
                }
                pm=pm.replaceFirst(",","");
                activity.setPaymentMethod(pm);
            }
            convertActivityPropertyToViewName(activity,ReductionActivity::setMemberLevel,ReductionActivity::getMemberLevel,gradeMap);
            convertActivityPropertyToViewName(activity,ReductionActivity::setMemberCategory,ReductionActivity::getMemberCategory,memberCategoryMap);
            convertActivityPropertyToViewName(activity,ReductionActivity::setCardType, ReductionActivity::getCardType,cardTypeMap);
            convertActivityPropertyToViewName(activity,ReductionActivity::setPhysicalCardType, ReductionActivity::getPhysicalCardType,physicalCardTypeMap);

            activity.setActivityUse(activityUseMap.get(activity.getActivityUse()));
            activity.setActivityMode(activityModeMap.get(activity.getActivityMode()));
            activity.setActivityType(activityTypeMap.get(activity.getActivityType()));
        }
        return getDataTable(list);
    }

    private void convertActivityPropertyToViewName(ReductionActivity activity, BiConsumer<ReductionActivity,String> setter, Function<ReductionActivity,String> getter, Map<String,String> viewMap){
        String property = getter.apply(activity);
        if (StringUtils.isBlank(property)) {
            return;
        }
        String[] split = property.split(",");
        StringJoiner joiner = new StringJoiner(",");
        for (String s : split) {
            joiner.add(viewMap.get(s));
        }
        setter.accept(activity,joiner.toString());
    }



    /**
     * 查询立减活动列表
     */
    @GetMapping("/labelActivityList")
    public TableDataInfo labelActivityList(ReductionActivity reductionActivity)
    {
        //历史数据查标签活动
        reductionActivity.setActivityUse("LABEl");
        List<ReductionActivity> list = reductionActivityService.selectActivityByLoginUser(reductionActivity);
        //新版本没有标签活动按标签用户查
        reductionActivity.setActivityUse(null);
        reductionActivity.setMemberTags(ReductionActivity.member_tags_labelUser);
        //
        reductionActivity.setActivityEnabled("1");
        List<ReductionActivity> list2 = reductionActivityService.selectActivityByLoginUser(reductionActivity);
        list.addAll(list2);
        list=list.stream().filter(r->r.getStartDate().before(new Date())&&r.getEndDate().after(new Date())).collect(Collectors.toList());

// 获取当前日期时间
        LocalDateTime today = LocalDateTime.now();

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

        for (ReductionActivity activity : list) {
            // 将活动的开始日期和结束日期转换为字符串类型
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String startDateStr = sdf.format(activity.getStartDate());
            String endDateStr = sdf.format(activity.getEndDate());

            // 将活动的开始日期和结束日期解析为LocalDateTime类型
            LocalDateTime startDate = LocalDateTime.parse(startDateStr, formatter);
            LocalDateTime endDate = LocalDateTime.parse(endDateStr, formatter);

            // 检查当前日期是否在活动日期范围内
            if (today.isAfter(startDate) && today.isBefore(endDate)) {
                activity.setActivityStatus("1");
            }else{
                activity.setActivityStatus("0");
            }

            //activity.setMemberLevel(gradeMap.get(activity.getMemberLevel()));
            if(activity.getPaymentMethod()!=null&&!activity.getPaymentMethod().contains(",")){
                activity.setPaymentMethod(payModeMap.get(activity.getPaymentMethod()));
            }
            if(activity.getPaymentMethod()!=null&&activity.getPaymentMethod().contains(",")){
                String[] split = activity.getPaymentMethod().split(",");
                String pm="";
                for (String s : split) {
                    pm=pm+","+payModeMap.get(s);
                }
                pm=pm.replaceFirst(",","");
                activity.setPaymentMethod(pm);
            }
            if(activity.getMemberLevel()!=null&&!activity.getMemberLevel().contains(",")){
                activity.setMemberLevel(gradeMap.get(activity.getMemberLevel()));
            }
            if(activity.getMemberLevel()!=null&&activity.getMemberLevel().contains(",")){
                String[] split = activity.getMemberLevel().split(",");
                String pm="";
                for (String s : split) {
                    pm=pm+","+gradeMap.get(s);
                }
                pm=pm.replaceFirst(",","");
                activity.setMemberLevel(pm);
            }

            activity.setActivityUse(activityUseMap.get(activity.getActivityUse()));
            activity.setActivityMode(activityModeMap.get(activity.getActivityMode()));
            activity.setActivityType(activityTypeMap.get(activity.getActivityType()));
        }
        return getDataTable(list);
    }

    /**
     * 导出立减活动列表
     */
    @Log(title = "立减活动", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ReductionActivity reductionActivity)
    {
        reductionActivity.setActiveStatus("1");
        List<ReductionActivity> list = reductionActivityService.selectReductionActivityList(reductionActivity);
        for (ReductionActivity activity : list) {
            activity.setMemberLevel(gradeMap.get(activity.getMemberLevel()));
            activity.setPaymentMethod(payModeMap.get(activity.getPaymentMethod()));
            activity.setActivityUse(activityUseMap.get(activity.getActivityUse()));
            activity.setActivityMode(activityModeMap.get(activity.getActivityMode()));
            activity.setActivityType(activityTypeMap.get(activity.getActivityType()));
        }
        ExcelUtil<ReductionActivity> util = new ExcelUtil<ReductionActivity>(ReductionActivity.class);
        return util.exportExcel(list, "reductionActivity");
    }

    /**
     * 获取立减活动详细信息
     */
    @GetMapping(value = "/{activityId}")
    public AjaxResult getInfo(@PathVariable("activityId") Long activityId)
    {

        Map<String, Object> stringObjectMap = reductionActivityService.selectActivityInfoByActivityId(activityId);

        //System.out.println(AjaxResult.success(stringObjectMap));
        return AjaxResult.success(stringObjectMap);
    }

    /**
     * 新增立减活动
     */
    @Log(title = "立减活动", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody String requestJson )  {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        logger.info(requestJson);
//        if(StringUtils.isEmpty(requestJson)){
//        }
        //JSON parse = (JSON) JSON.parse(requestJson);
        //解析json
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("requestJson",requestJson);
        params.put("currentUser",currentUser);
        Long activityId = null;
        try {
            activityId = reductionActivityService.insertReductionActivity(params);
            JSONObject jsonObject = JSONObject.parseObject(requestJson);
            String wxContent = jsonObject.getString("wxContent");
            Integer sendFlag = jsonObject.getInteger("sendFlag");
            activityMessagePushRecordService.sendWxMessage(activityId, ActivityMessagePushRecord.REDUCTION_ACTIVITY,wxContent,sendFlag);
        } catch (ParseException e) {
            logger.error(e.getMessage(),e);
        }
        //AjaxResult result = new AjaxResult();
        //Map<String,Object> data = new HashMap<String,Object>();
//        return toAjax(reductionActivityService.insertReductionActivity(reductionActivity));
        return activityId != null?AjaxResult.success(activityId):AjaxResult.error();
    }

    /**
     * 修改立减活动
     */
//    @Log(title = "立减活动", businessType = BusinessType.UPDATE)
//    @PutMapping
//    public AjaxResult edit(@RequestBody ReductionActivity reductionActivity)
//    {
//        return toAjax(reductionActivityService.updateReductionActivity(reductionActivity));
//    }

    /**
     * 删除立减活动
     */
    @Log(title = "立减活动", businessType = BusinessType.DELETE)
	@DeleteMapping("/{activityIds}")
    public AjaxResult remove(@PathVariable Long[] activityIds)
    {
        return toAjax(reductionActivityService.deleteReductionActivityByIds(activityIds));
    }

    @Log(title = "立减活动", businessType = BusinessType.UPDATE)
    @GetMapping("changeActivityEnabled")
    public AjaxResult changeActivityEnabled(@RequestParam("activityId") Long id){
        reductionActivityService.changeActivityEnabled(id);
        return AjaxResult.success();
    }
}
